global input "Q:\dc1prhcmsas01\PU2\data - sas"
global temp "Q:\dc1prhcmsas01\PU2\temp_stata_wr"
global log "Q:\dc1prhcmsas01\PU2\Log - Stata WR"
global output "Q:\dc1prhcmsas01\PU2\data_stata_wr"
global graphs "Q:\dc1prhcmsas01\PU2\graphs_stata_wr"
global tables "Q:\dc1prhcmsas01\PU2\tables_stata_wr"

cd "Q:\dc1prhcmsas01\PU2\Code - Stata WR"

capture log close
log using "$log/4_balanced_workers_wr", replace


*Loop over 37 months
cap program drop balanced
program define balanced 
args year month ref
clear all 

	forvalues i=0/36 {
	    local m=mod(`month'-1+`i',12)+1
	    local y=`year'+int((`month'-1+`i')/12)
		
		*Import
		capture use state client_id emp_pur_c using "$temp\cleaned_`y'`m'", clear
		capture use state client_id emp_pur_c using "$temp\cleaned_`y'0`m'", clear
		
		*Keep balanced firms
		merge m:1 client_id using "$output/balanced_firms_`ref'"
		keep if _merge==3
		drop _merge
				
		*Save
		compress
		save "$temp\workers_`i'.dta", replace
	}

	*Keep only workers who are in every month of the year
	use "$temp\workers_0.dta", clear
	forvalues i=1/36 {
	    merge 1:1 state client_id emp_pur_c using "$temp\workers_`i'.dta"
		keep if _merge==3 
		drop _merge
	}

	save "$temp\balanced_workers_`ref'.dta", replace
end

balanced 2015 5 treat 
balanced 2013 5 control 

*Delete temp files
forvalues i=0/36 {
	erase "$temp\workers_`i'.dta"
}

log close